<script setup>
import { ref } from 'vue'

const props = defineProps({
  placeholder: {
    type: String,
    default: '搜索'
  },
  value: {
    type: String,
    default: ''
  },
  bgColor: {
    type: String,
    default: 'rgba(255, 255, 255, 0.9)'
  },
  showCancel: {
    type: Boolean,
    default: false
  },
  radius: {
    type: String,
    default: '12rpx'
  }
})

const emit = defineEmits(['update:value', 'search', 'focus', 'blur', 'clear', 'cancel'])

const keyword = ref(props.value)
const isFocused = ref(false)

const onInput = (e) => {
  keyword.value = e.detail.value
  emit('update:value', e.detail.value)
}

const onSearch = () => {
  emit('search', keyword.value)
}

const onFocus = () => {
  isFocused.value = true
  emit('focus')
}

const onBlur = () => {
  isFocused.value = false
  emit('blur')
}

const onClear = () => {
  keyword.value = ''
  emit('update:value', '')
  emit('clear')
}

const onCancel = () => {
  keyword.value = ''
  emit('update:value', '')
  emit('cancel')
}
</script>

<template>
  <view class="search-bar">
    <view 
      class="search-input-wrap"
      :style="{ 
        backgroundColor: bgColor,
        borderRadius: radius,
        flex: showCancel ? '1' : 'none',
        width: showCancel ? 'auto' : '100%'
      }"
    >
      <image src="/static/icons/search.png" class="search-icon" mode="aspectFit" />
      <input
        type="text"
        :value="keyword"
        :placeholder="placeholder"
        placeholder-class="placeholder"
        confirm-type="search"
        @input="onInput"
        @confirm="onSearch"
        @focus="onFocus"
        @blur="onBlur"
      />
      <view v-if="keyword" class="clear-btn" @tap="onClear">
        <image src="/static/icons/close-circle.png" mode="aspectFit" />
      </view>
    </view>
    <view v-if="showCancel" class="cancel-btn" @tap="onCancel">取消</view>
  </view>
</template>

<style lang="scss" scoped>
.search-bar {
  display: flex;
  align-items: center;
  padding: 16rpx 32rpx;
  
  .search-input-wrap {
    height: 72rpx;
    display: flex;
    align-items: center;
    padding: 0 24rpx;
    
    .search-icon {
      width: 32rpx;
      height: 32rpx;
      margin-right: 16rpx;
      opacity: 0.5;
    }
    
    input {
      flex: 1;
      height: 100%;
      font-size: 28rpx;
    }
    
    .placeholder {
      color: #999;
      font-size: 28rpx;
    }
    
    .clear-btn {
      padding: 8rpx;
      margin-left: 8rpx;
      
      image {
        width: 32rpx;
        height: 32rpx;
        opacity: 0.3;
      }
    }
  }
  
  .cancel-btn {
    padding: 0 24rpx;
    font-size: 28rpx;
    color: #666;
  }
}
</style> 